package com.lanzuo.yxd.scanner.scanner;

import com.lanzuo.yxd.scanner.scanner.handler.ScannerClientHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author eric
 * 海康扫码枪对接
 */
@Slf4j
public class ScannerClient {
    private static final String T1 = "T1";
    private static final byte[] SCAN_COMMAND = T1.getBytes(StandardCharsets.UTF_8);
    private static final int PORT = 2001;
    private static final int RECONNECT_DELAY_SECONDS = 3;
    private final NioSocketConnector connector = new NioSocketConnector();
    private final AtomicBoolean connected = new AtomicBoolean(false);
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private String host;
    private String position;
    private Integer lane;
    private IoSession session;

    public ScannerClient(Integer lane, String host, String position) {
        this.lane = lane;
        this.host = host;
        this.position = position;

        this.connector.setHandler(new ScannerClientHandler(this.lane, this.host, this.position) {

            // 重写这个方法
            @Override
            public void onDisconnection() {
//                handleDisconnection();
            }
        });

        start();
    }

    /**
     * 启动连接
     */
    private void start() {
        log.info("正在连接到{}扫码枪服务端 {}:{}", position, host, PORT);
        ConnectFuture future = connector.connect(new InetSocketAddress(host, PORT));
        future.awaitUninterruptibly();

        if (future.isConnected()) {
            session = future.getSession();
            connected.set(true);
            log.info("✅ start 成功连接到服务端 {}:{}", host, PORT);
        } else {
            log.warn("❌ 连接失败，请检查网络");
        }
    }

    /**
     * 启动连接， 带断线重连
     */
//    private void reTryStart() {
//        log.info("正在连接到服务端 {}:{}", host, PORT);
//        ConnectFuture future = connector.connect(new InetSocketAddress(host, PORT));
//        future.awaitUninterruptibly();
//
//        if (future.isConnected()) {
//            session = future.getSession();
//            connected.set(true);
//            log.info("✅ 成功连接到服务端 {}:{}", host, PORT);
//        } else {
//            log.warn("❌ 连接失败，将在 {} 秒后重试...", RECONNECT_DELAY_SECONDS);
//            scheduleReconnect();
//        }
//    }
    public void sendT1() {
        if (!connected.get() || session == null || !session.isConnected()) {
            log.warn("⚠️ 未连接，无法发送 T1");
            return;
        }

        try {
            session.write(IoBuffer.wrap(SCAN_COMMAND));
        } catch (Exception e) {
            log.error("发送 T1 失败", e);
//            handleDisconnection();
        }
    }

    /**
     * 断连处理
     */
    private void handleDisconnection() {
        connected.set(false);
        if (session != null && !session.isClosing()) {
            session.closeOnFlush();
        }
        log.warn("🔌 连接断开，将在 {} 秒后重连...", RECONNECT_DELAY_SECONDS);
        scheduleReconnect();
    }

    private void scheduleReconnect() {
        scheduler.schedule(this::reconnect, RECONNECT_DELAY_SECONDS, TimeUnit.SECONDS);
    }

    private void reconnect() {
        if (connected.get()) return;
//        reTryStart();
    }

    @PreDestroy
    public void destroy() {
        log.info("正在关闭 MINA_SCANNER 客户端...");
        if (session != null) {
            session.closeOnFlush();
        }
        connector.dispose();
        scheduler.shutdown();
        log.info("MINA_SCANNER 客户端已关闭");
    }


}
